package com.zzyl.nursing.service.impl;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Arrays;

import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * 入住Service业务层处理
 * 
 * @author SumJane
 * @date 2025-07-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        checkIn.setCreateTime(DateUtils.getNowDate());
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        checkIn.setUpdateTime(DateUtils.getNowDate());
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /***
     * 新增入住信息
     * */
    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
//        1、核对是否存在(是否曾经入住过)
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus,1);
        Elder elder = new Elder();
        Elder one = elderMapper.selectOne(wrapper);
        if (one != null) {    //数据库存在就跳过
            BeanUtils.copyProperties(one,elder);
            throw new RuntimeException("该老人已入住过");
        }
        BeanUtils.copyProperties(dto.getCheckInElderDto(),elder);
//        2、(未入住分流)锁死床位(前面会展示未入住的床位,所以这里只需要选择用户搜索的床位id并变成1)
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateBed(bed);
//        3、保存老人数据
        elderMapper.insert(elder);
//        4、保存合同数据
        extracted(dto, elder);
//        5、保存入住数据
        CheckIn checkIn = getCheckIn(dto, elder, bed);
//        6、保存入住配置数据 CheckInConfig
        extracted(dto, checkIn);
    }
    /***
     * 查询回显*/
    @Override
    public CheckInDetailVo detail( Integer id) {
        //        3、获取入住配置
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        LambdaQueryWrapper<CheckIn> wrapper = Wrappers.<CheckIn>lambdaQuery().eq(CheckIn::getId, id);
        CheckIn checkIn = checkInMapper.selectOne(wrapper);
        if (checkIn == null) {
            throw new RuntimeException("入住记录不存在");
        }
        ///////////////////////////////////////////////////////////////////
        LambdaQueryWrapper<CheckInConfig> wrapper1 = Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(wrapper1);
        if (checkInConfig == null) {
            throw new RuntimeException("入住详情不存在");
        }
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
///////////////////////////////////////////////////////////////////
//        1、获取老人相应信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        if (elder == null) {
            throw new RuntimeException("老人信息不存在");
        }
        BeanUtils.copyProperties(elder,checkInElderVo);
        ///////////////////////////////////////////////////////////////////
//        2、获取家属信息
        ArrayList<ElderFamilyVo> elderFamilyVo = new ArrayList<>();
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(checkIn.getRemark(), ElderFamilyVo.class);
        ///////////////////////////////////////////////////////////////////
//        4、获取签约办理
        LambdaQueryWrapper<Contract> wrapper2 = Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, checkIn.getElderId());
        Contract contract = contractMapper.selectOne(wrapper2);
        ///////////////////////////////////////////////////////////////////
//        汇总回传
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo().builder()
                        .checkInConfigVo(checkInConfigVo)
                        .elderFamilyVoList(elderFamilyVoList)
                        .checkInElderVo(checkInElderVo)
                        .contract(contract).build();
        return checkInDetailVo;
    }

    private void extracted(CheckInApplyDto dto, Elder elder) {
        //生成合同编号
        String contractNo = "HT"+ CodeGenerator.generateContractNumber();
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(),contract);
//        其他字段
        contract.setContractNumber(contractNo);
        //强转
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        //状态、开始时间、结束时间
        //签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = dto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isAfter(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contract.setStartDate(new Date());
        contract.setEndDate(new Date());
        contract.setSignDate(new Date());
        contractMapper.insert(contract);
    }

    private CheckIn getCheckIn(CheckInApplyDto dto, Elder elder, Bed bed) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkIn);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkIn.setBedNumber(bed.getBedNumber());
        int insert = checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void extracted(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setFeeStartDate(dto.getCheckInConfigDto().getStartDate());
        checkInConfig.setFeeEndDate(dto.getCheckInConfigDto().getFeeEndDate());
        checkInConfigMapper.insert(checkInConfig);
    }
}
